package com.niiwoo.civet.user.service.local;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.user.dao.entity.*;
import com.niiwoo.civet.user.dao.mapper.*;
import com.niiwoo.civet.user.dto.request.AssetPortraitAuthRequestDTO;
import com.niiwoo.civet.user.dto.response.UserAuthorizationInfoResponseDTO;
import com.niiwoo.civet.user.enums.PortraitChannelEnum;
import com.niiwoo.civet.user.enums.UserDataStatusEnum;
import com.niiwoo.civet.user.enums.UserDataTypeEnum;
import com.niiwoo.tripod.tiancheng.response.auth.faceid.FaceIdVerifyResp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * face++肖像认证本地服务
 */
@Service
public class FacePlusPortraitService implements LoginAccountRedisService {

    @Autowired
    FacePlusPortraitMapperExt facePlusPortraitMapperExt;

    @Autowired
    FacePlusPortraitRecordMapperExt facePlusPortraitRecordMapperExt;

    @Autowired
    DataStatusMapperExt dataStatusMapperExt;

    @Autowired
    UserAuthorizationInfoMapperExt userAuthorizationInfoMapperExt;

    @Autowired
    IdentityMappingMapper identityMappingMapper;

    @Autowired
    StringRedisTemplate template;

    @Autowired
    private UserAuthorizationInfoService userAuthorizationInfoService;

    @Autowired
    UserStatusService userStatusService;

    @Override
    public RedisTemplate<String, String> getStringRedisTemplate() {
        return template;
    }

    public FacePlusPortrait getFacePlusPortraitByUserId(String userId) {
        return facePlusPortraitMapperExt.selectByPrimaryKey(userId);
    }

    /**
     * 保存历史记录
     */
    public boolean saveHistoryRecord(FacePlusPortraitRecord record) {
        return facePlusPortraitRecordMapperExt.insertSelective(record) > 0;
    }

    /**
     * 保存肖像认证信息
     *  @param updateRecord face++ 肖像认证历史记录
     * @param isAuthRecordExists face++ 肖像认证记录是否存在
     * @param updateFacePlusPortrait face++ 肖像认证记录
     * @param isPortraitStatusExists 肖像认证状态记录是否存在
     * @param updatePortraitStatus 肖像认证状态记录
     * @param updateAuthorizationInfo 用户授权信息
     * @param isTwoElementPass 是否更新二要素
     * @param isTwoElementExists 二要素记录是否存在
     * @param twoElementStatus 二要素状态记录
     * @param identityMapping 身份映射记录
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public boolean saveAuthAndHistoryRecord(FacePlusPortraitRecord updateRecord, boolean isAuthRecordExists, FacePlusPortrait updateFacePlusPortrait, boolean isPortraitStatusExists, DataStatus updatePortraitStatus, UserAuthorizationInfo updateAuthorizationInfo, boolean isTwoElementPass, boolean isTwoElementExists, DataStatus twoElementStatus, IdentityMapping identityMapping) {
        boolean isSaveSuccess = facePlusPortraitRecordMapperExt.updateByPrimaryKeySelective(updateRecord) > 0 &&
                                // 保存认证记录
                                (isAuthRecordExists ? facePlusPortraitMapperExt.updateByPrimaryKeySelective(updateFacePlusPortrait) > 0 : facePlusPortraitMapperExt.insertSelective(updateFacePlusPortrait) > 0) &&
                                // 保存认证状态记录
                                (isPortraitStatusExists ? dataStatusMapperExt.updateByUserIdAndType(updatePortraitStatus) > 0 : dataStatusMapperExt.insertSelective(updatePortraitStatus) > 0) &&
                                // 保存肖像认证通道信息
                                userAuthorizationInfoMapperExt.updateByPrimaryKeySelective(updateAuthorizationInfo) > 0;
        // 是否更新二要素状态记录
        if(isTwoElementPass) {
            boolean isTwoElementUpdateSuccess = isTwoElementExists ? dataStatusMapperExt.updateByUserIdAndTypeIfPossible(twoElementStatus, UserDataStatusEnum.RealNameAuthStatus.PASS_CERTIFIED.getStatus()) > 0 : dataStatusMapperExt.insertSelective(twoElementStatus) > 0;
            // 身份映射不存在则新增
            if (isTwoElementUpdateSuccess && identityMappingMapper.selectByPrimaryKey(identityMapping.getIdCard()) == null) {
                identityMappingMapper.insertSelective(identityMapping);
            }
        }
        return isSaveSuccess;



    }

    // 0: 更新失败， 1：更新成功
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int updateBestImg4R360(AssetPortraitAuthRequestDTO requestDTO){

        UserAuthorizationInfoResponseDTO userAuthResponse = userAuthorizationInfoService.getUserAuthorizationInfo(requestDTO.getUserId());
        if (userAuthResponse != null) {
            if (userAuthResponse.getFaceVerificationChannel() == PortraitChannelEnum.FACE_PLUS.getValue()) {
                FacePlusPortrait updateFacePlusPortrait = new FacePlusPortrait();
                updateFacePlusPortrait.setUserId(requestDTO.getUserId());
                updateFacePlusPortrait.setBestLiveImage(requestDTO.getLiveImageUrl());
                if (StringUtils.isNotEmpty(requestDTO.getConfidence())) {
                    updateFacePlusPortrait.setLiveImageConfidence(Double.valueOf(requestDTO.getConfidence()));
                }

                if (StringUtils.isNotEmpty(requestDTO.getThresholds())) {
                    FaceIdVerifyResp.Thresholds thresholds =  JSON.parseObject(requestDTO.getThresholds(),FaceIdVerifyResp.Thresholds.class);
                    if (thresholds != null) {
                        updateFacePlusPortrait.setLiveImageThreshold1e3(thresholds.getOne_e_3().doubleValue());
                        updateFacePlusPortrait.setLiveImageThreshold1e4(thresholds.getOne_e_4().doubleValue());
                        updateFacePlusPortrait.setLiveImageThreshold1e5(thresholds.getOne_e_5().doubleValue());
                        updateFacePlusPortrait.setLiveImageThreshold1e6(thresholds.getOne_e_6().doubleValue());
                    }
                }

                updateFacePlusPortrait.setUpdateTime(new Date());

                return facePlusPortraitMapperExt.updateByPrimaryKeySelective(updateFacePlusPortrait);
            } else {
                //TODO WPING 更新商汤图片
                return 1;
            }
        }
        return 0;
    }

    // 0: 更新失败， 1：更新成功
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int updatePortraitAuthStatus2NeedApprove4R360(String userId){

        List<DataStatus> list = Optional.ofNullable(userStatusService.getDataStatusByUserId(userId)).orElse(Collections.EMPTY_LIST);
        boolean isPortraitAuth = list.stream()
                .anyMatch(s ->
                        Objects.equals(s.getDataType(), UserDataTypeEnum.PORTRAIT.getValue()) &&
                                UserDataStatusEnum.PortraitAuthStatus.except(s.getDataStatus(), UserDataStatusEnum.PortraitAuthStatus.PASS_CERTIFIED, UserDataStatusEnum.PortraitAuthStatus.NEED_APPROVE)
                );
        if (isPortraitAuth) {
            return 1;
        }

        Optional<DataStatus> oldPortraitAuthStatusOpt = list.stream()
                .filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.PORTRAIT.getValue()))
                .findFirst();

        if (oldPortraitAuthStatusOpt.isPresent()) {
            DataStatus updatePortraitStatus = new DataStatus();
            updatePortraitStatus.setDataStatus(UserDataStatusEnum.PortraitAuthStatus.NEED_APPROVE.getStatus());
            updatePortraitStatus.setId(oldPortraitAuthStatusOpt.get().getId());
            updatePortraitStatus.setUpdateTime(new Date());

            dataStatusMapperExt.updateByPrimaryKeySelective(updatePortraitStatus);
        }

        return 1;
    }
}
